const playButton = document.querySelector(".play-button");
const prevButton = document.querySelector(".prev-button");
const nextButton = document.querySelector(".next-button");
const settingsButton = document.querySelector(".settings-button");
const volumeButton = document.getElementById("volumeButton");
const volumeControl = document.getElementById("volumeControl");
const currentTimeDisplay = document.getElementById("current-time");
const durationDisplay = document.getElementById("duration");
const progressBar = document.getElementById("progress");
const volumeSlider = document.getElementById("volumeSlider");
const volumeIcon = volumeButton.querySelector("i");
const playModeButton = document.getElementById("playModeButton");
const playModeIcon = document.getElementById("playModeIcon");

// 保存原始音量值
let originalVolume = audio.volume;

// 初始化当前时间为 00:00
currentTimeDisplay.textContent = formatTime(0);

// 播放模式
let playMode = "normal"; // normal, repeat, shuffle

// 当前播放默认的输入的情况
let shuffleInput = false;

// 播放 / 暂停
playButton.addEventListener("click", function () {
  if (audio.paused) {
    audioPlay();
    playButton.querySelector("i").classList.replace("fa-play", "fa-pause");
    // 修改快捷键提示
    playButton.querySelector("i").title = "暂停（P）";
  } else {
    audio.pause();
    playButton.querySelector("i").classList.replace("fa-pause", "fa-play");
    // 修改快捷键提示
    playButton.querySelector("i").title = "播放（P）";
  }

  // 当前歌曲动画切换
  playState();
});

// Progress Bar
audio.addEventListener("timeupdate", function () {
  const progress = (audio.currentTime / audio.duration) * 100;
  progressBar.style.width = `${progress}%`;
  currentTimeDisplay.textContent = formatTime(audio.currentTime);
  if (audio.duration) {
    durationDisplay.textContent = formatTime(audio.duration);
  }
});

// 点击进度条时跳转到指定位置
const progressBarContainer = document.querySelector(".progress-bar");
progressBarContainer.addEventListener("click", function (event) {
  if (progressBarContainer && audio.networkState !== audio.NETWORK_NO_SOURCE) {
    // 检查音频是否已准备好播放
    if (audio.readyState >= audio.HAVE_ENOUGH_DATA) {
      const rect = progressBarContainer.getBoundingClientRect();
      const clickX = event.clientX - rect.left;
      const newTime = (clickX / rect.width) * audio.duration;
      audio.currentTime = newTime;
    } else {
      // 如果歌曲缓存中
      console.warn("%c 歌曲缓存中...", "color: goldenrod;");
    }
  } else {
    // 如果歌曲缓存异常
    console.warn("%c 歌曲缓存异常...", "color: goldenrod;");
  }
});

// Previous Button
prevButton.addEventListener("click", function () {
  mp3Index = (mp3Index - 1 + arr.length) % arr.length;
  show(mp3Index);

  audio.currentTime = 0;
  audioPlay();

  // 直接定位到当前歌曲位置
  scrollToCurrentSong();

  // 当前歌曲动画切换
  playState();
});

// Next Button
nextButton.addEventListener("click", function () {
  mp3Index = (mp3Index + 1) % arr.length;
  show(mp3Index);

  // 直接定位到当前歌曲位置
  scrollToCurrentSong();

  switch (playMode) {
    case "normal":
      audio.currentTime = 0;
      audioPlay();
      break;
    case "repeat":
      audio.currentTime = 0;
      audioPlay();
      break;
    case "shuffle":
      // 假设有一个函数来随机选择下一首歌曲
      playRandomSong();
      break;
  }

  // 当前歌曲动画切换
  playState();
});

// 更新图标
function updatePlayModeIcon() {
  if (playMode === "normal") {
    playModeIcon.classList.remove("fas", "fa-random", "fas", "fa-redo-alt");
    playModeIcon.classList.add("fas", "fa-exchange-alt");
    // 修改快捷键提示
    playModeIcon.title = "顺序播放（L）";
  } else if (playMode === "shuffle") {
    playModeIcon.classList.remove(
      "fas",
      "fa-exchange-alt",
      "fas",
      "fa-redo-alt"
    );
    // 修改快捷键提示
    playModeIcon.title = "随机播放（L）";
    playModeIcon.classList.add("fas", "fa-random");
  } else if (playMode === "repeat") {
    playModeIcon.classList.remove("fas", "fa-list-ol", "fas", "fa-random");
    playModeIcon.classList.add("fas", "fa-redo-alt");
    // 修改快捷键提示
    playModeIcon.title = "单曲循环（L）";
  }
}

// 更新音频的 loop 属性
function updateAudioLoop() {
  audio.loop = playMode === "repeat";
}

// 初始化图标和音频循环属性
updatePlayModeIcon();
updateAudioLoop();

// 播放模式按钮
playModeButton.addEventListener("click", function () {
  if (playMode === "normal") {
    playMode = "shuffle";
  } else if (playMode === "shuffle") {
    playMode = "repeat";
  } else if (playMode === "repeat") {
    playMode = "normal";
  }

  // 更新图标和音频循环属性
  updatePlayModeIcon();
  updateAudioLoop();
});

// 设置按钮图标切换
let isSettingsIconList = true; // 初始状态为 fa-list 图标

function toggleView() {
  const settingsIcon = settingsButton.querySelector("i");
  const listTop = document.querySelector(".listTop");

  if (isSettingsIconList) {
    // 切换到 fa-bars 图标
    settingsIcon.classList.remove("fas", "fa-list");
    settingsIcon.classList.add("fas", "fa-bars");

    // 修改快捷键提示
    settingsIcon.title = "歌词界面（H）";

    // 隐藏歌词按钮 隐藏歌曲列表按钮
    lyricsList.style.display = "none";
    // 隐藏按钮
    detailButton.style.display = "none";
    floatingDiv.style.display = "block";
    listTop.style.display = "block";

    // 进入歌曲列表就调整
    playListHeight();

    // 如果是随机播放模式，就让列表滚动条 滚到 最下面
    if (playMode === "shuffle") {
      // 获取歌曲列表
      const playList = document.querySelector(".playList>.content>ul");
      // 使用 scrollTo 方法滑动到底部
      playList.scrollTo({
        top: playList.scrollHeight, // 设置 top 为 scrollHeight 来滚动到底部
        left: 0, // 保持水平滚动位置不变（如果适用）
        behavior: "auto", // 可选：定义滚动行为为平滑滚动
      });
      shuffleInput = true;
    }
  } else {
    // 切换回 fa-list 图标
    settingsIcon.classList.remove("fas", "fa-bars");
    settingsIcon.classList.add("fas", "fa-list");

    // 修改快捷键提示
    settingsIcon.title = "歌曲列表（H）";

    // 显示歌词
    lyricsList.style.display = "block";
    // 显示按钮
    detailButton.style.display = "block";
    floatingDiv.style.display = "none";
    listTop.style.display = "none";

    // 进入歌词模式就调整
    lyricsListHeight();
  }
  isSettingsIconList = !isSettingsIconList; // 切换状态

  // 直接定位到当前歌曲位置
  setTimeout(scrollToCurrentSong, 100);
}

settingsButton.addEventListener("click", toggleView);

// 随机播放歌曲函数
function playRandomSong() {
  let currentSongIndex = mp3Index; // 假设mp3Index是当前歌曲的索引

  // 如果arr数组长度为1或更小，则直接播放该唯一的一首歌
  if (arr.length <= 1) {
    mp3Index = 0;
  } else {
    do {
      mp3Index = Math.floor(Math.random() * arr.length);
    } while (mp3Index === currentSongIndex); // 确保新索引不同于当前索引
  }
}

// 初始化时从 localStorage 读取音量值
const storedVolume = localStorage.getItem("volume");
if (storedVolume !== null) {
  audio.volume = parseFloat(storedVolume);
  volumeSlider.value = audio.volume;

  // 确保图标根据存储的音量值更新
  updateVolumeIcon(audio.volume);
} else {
  // 如果没有存储的音量值，默认设置音量和图标
  audio.volume = 0.5; // 或者你想要的默认音量值
  volumeSlider.value = audio.volume;
  updateVolumeIcon(audio.volume);
}

// Volume Control
volumeSlider.addEventListener("input", function () {
  audio.volume = this.value;
  if (audio.muted) {
    audio.muted = false; // 如果当前是静音状态，取消静音
  }
  updateVolumeIcon(this.value); // 更新音量图标

  // 存储音量到 localStorage
  localStorage.setItem("volume", this.value);
});

// Volume Icon Click
volumeIcon.addEventListener("click", function () {
  if (audio.muted) {
    // 如果当前是静音状态，恢复音量
    audio.muted = false;
    audio.volume = originalVolume;
    volumeSlider.value = originalVolume;
  } else {
    // 如果当前不是静音状态，设置为静音
    originalVolume = audio.volume; // 保存当前音量
    audio.muted = true;
    volumeSlider.value = 0; // 设置音量滑块为0
  }

  // 更新音量图标
  updateVolumeIcon(audio.volume);

  // 存储音量到 localStorage
  localStorage.setItem("volume", audio.volume.toString());
});

// 更新音量图标
function updateVolumeIcon(volume) {
  if (volume === 0 || audio.muted) {
    volumeIcon.classList.remove("fas", "fa-volume-up", "fa-volume-down");
    volumeIcon.classList.add("fas", "fa-volume-mute");
  } else if (volume < 0.5) {
    volumeIcon.classList.remove("fas", "fa-volume-up", "fa-volume-mute");
    volumeIcon.classList.add("fas", "fa-volume-down");
  } else {
    volumeIcon.classList.remove("fas", "fa-volume-down", "fa-volume-mute");
    volumeIcon.classList.add("fas", "fa-volume-up");
  }
}

// Hide volume control when mouse leaves
volumeControl.addEventListener("mouseleave", function () {
  volumeControl.style.display = "none";
});

// Volume Button
volumeButton.addEventListener("click", function () {
  volumeControl.style.display =
    volumeControl.style.display === "none" ? "flex" : "none";
});

// Format Time
function formatTime(seconds) {
  const minutes = Math.floor(seconds / 60)
    .toString()
    .padStart(2, "0"); // 确保分钟数为两位数
  const remainingSeconds = Math.floor(seconds % 60)
    .toString()
    .padStart(2, "0"); // 确保秒数为两位数
  return `${minutes}:${remainingSeconds}`;
}

// 在移动端使用触摸事件
document.addEventListener("touchstart", function (event) {
  const target = event.target;
  if (!volumeControl.contains(target) && target !== volumeButton) {
    volumeControl.style.display = "none";
  }
});

document.addEventListener("touchend", function (event) {
  const target = event.target;
  if (!volumeControl.contains(target) && target !== volumeButton) {
    volumeControl.style.display = "none";
  }
});
